package com.maben.udp.test004.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

/**
 * 服务端处理器
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        DatagramPacket packet = (DatagramPacket) msg;
        final ByteBuf buf = packet.content();
        System.out.println("server receive msg: " + buf.toString(CharsetUtil.UTF_8));
        //收到客户端信息，给客户端回复一下
        ByteBuf res = Unpooled.wrappedBuffer(("server received_" + buf.toString(CharsetUtil.UTF_8)).getBytes());
        ctx.writeAndFlush(res);
    }


    /**
     * 连接成功后，自动执行该方法
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("connect success!");
        /*
         * 这种发送的消息格式是错误的!!!!!
         * 消息格式必须是ByteBuf才行!!!!!
         */
//        ctx.writeAndFlush("Hello is server !");
    }

    /**
     * 处理异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }
}
